package jdk.thread.tool;

import java.util.concurrent.Phaser;

/**
 * Phaser-移相器
 * phase-阶段
 * Advance-前进
 * wait-等待
 * arrive-到达
 * Deregister-注销
 *
 * 据说和CountDownLatch和CyclicBarrier用法相近，只是功能更灵活更强大！！
 */
public class PhaserTest {

    public static void main(String[] args) throws InterruptedException {
        int number = 5;

        GamePhaser phaser = new GamePhaser();
        phaser.bulkRegister(number);
        for(int i=0;i<5;i++){
            System.out.println(i+"号选手已出发！！");
            new GamePalyer(phaser).start();
        }

        System.out.println("选手已全部出发！！");



//        Phaser phaser = new Phaser();
//        phaser.register();
//        phaser.bulkRegister(10);
//        phaser.wait();
//        phaser.arrive();
//        phaser.arriveAndAwaitAdvance();
//        phaser.arriveAndDeregister();
    }


}

class GamePhaser extends Phaser{
    @Override
    protected boolean onAdvance(int phase, int registeredParties) {
        switch (phase) {
            case 0 :
                System.out.println("预赛完成");
                return false;
            case 1:
                System.out.println("初赛完成");
                return false;
            case 2:
                System.out.println("决赛完成");
                return false;
            default:
                return true;
        }
    }
}


class GamePalyer extends Thread{


    Phaser phaser;

    GamePalyer(Phaser phaser){
        this.phaser = phaser;
    }

    @Override
    public void run() {
        System.out.println("选手["+getName()+"]通过第一关");
        phaser.arriveAndAwaitAdvance();
        System.out.println("选手["+getName()+"]通过第二关");
        phaser.arriveAndAwaitAdvance();
        System.out.println("选手["+getName()+"]通过第三关");
        phaser.arriveAndAwaitAdvance();
    }
}
